# chat/consumers.py
from asgiref.sync import async_to_sync
import json
from channels.generic.websocket import WebsocketConsumer
from user.models import UserModel
from shops.models import ShopsModel
from chat.models import Speaking

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'chat_%s' % self.room_name

        # Join room group
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )

        self.accept()
    def disconnect(self, close_code):
        # Leave room group
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )

    # 收到消息
    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        print('receive接收到的text_data_json', text_data_json)
        # message = text_data_json['message']
        # print("发送的内容》》",message)
        # user_id = text_data_json['user_id']
        # bid = text_data_json['bid']
        # status = text_data_json['status']
        # chatid = text_data_json['chat_id']
        # print("发送的ID》》", status)
        # # self.room_name.split("_")[0]
        # if status == 0:
        #     # Speaking.objects.create(uid_id=user_id,bid_id=bid,speatxt=message,reply=status)
        #     user = UserModel.objects.get(id = user_id)
        #     text_data_json['uname'] = user.name
        #     text_data_json['uid'] = user.id
        #
        # if status == 1:
        #     busin = ShopsModel.objects.get(id = bid)
        #     text_data_json['bname'] = busin.name
        #     text_data_json['bid'] = busin.id
        # Speaking.objects.create(uid_id=user_id, bid_id=bid, speatxt=message, reply=status,chatid=chatid)

        text_data_json["type"] = "chat_message"
        # Send message to room group       向文件室组发送消息(将text_data_json发送给前端)
        async_to_sync(self.channel_layer.group_send)(self.room_group_name,text_data_json)

    # Receive message from room group  从文件室组接收消息
    # 聊天——信息
    def chat_message(self, event):
        print('chat_message接收到的消息', event)

        # Send message to WebSocket
        self.send(text_data=json.dumps(event))
